package org.dromara.iot.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.ImageUtil;
import org.dromara.common.mqtt.handler.MqttMessageHandler;
import org.dromara.iot.domain.bo.IotElevatorEventBo;
import org.dromara.iot.domain.mq.ForbiddenItemEvent;
import org.dromara.iot.domain.vo.IotElevatorVo;
import org.dromara.iot.enums.BusinessCodeEnum;
import org.dromara.iot.enums.ElevatorEventTypeEnum;
import org.dromara.iot.enums.ForbiddenItemAlarmEnum;
import org.dromara.iot.service.IIotElevatorEventService;
import org.dromara.iot.service.IIotElevatorService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

import java.io.File;

@Slf4j
@RequiredArgsConstructor
@Service
public class ForbiddenItemMessageHandler implements MqttMessageHandler {
    private final IIotElevatorService elevatorService;
    private final ISysOssService ossService;
    private final IIotElevatorEventService elevatorEventService;

    @Override
    public void handle(String code, MqttMessage message) {
        IotElevatorVo iotElevator = elevatorService.selectByRegisteredCode(code);
        if (iotElevator == null) {
            log.error("接收到状态消息，但电梯不存在:{}", code);
            return;
        }
        ForbiddenItemEvent forbiddenItemEvent = JSONUtil.toBean(new String(message.getPayload()), ForbiddenItemEvent.class);
        String imagePath = ImageUtil.generateImage(forbiddenItemEvent.getImage());
        SysOssVo upload = ossService.upload(new File(imagePath));
        log.info("上传图片成功:{}", upload);
        ForbiddenItemAlarmEnum forbiddenItemAlarmEnum = ForbiddenItemAlarmEnum.getForbiddenItemAlarmEnum(forbiddenItemEvent.getEventType());
        if (forbiddenItemAlarmEnum == null) {
            log.error("接收到状态消息，但电梯状态不存在:{}", forbiddenItemEvent.getEventType());
            return;
        }
        IotElevatorEventBo bo = new IotElevatorEventBo();
        bo.setElevatorId(iotElevator.getElevatorId());
        bo.setEventCode(BusinessCodeEnum.ELEVATOR_EVENT.getBusinessCode());
        bo.setElevatorName(iotElevator.getElevatorName());
        bo.setEventType(ElevatorEventTypeEnum.FORBIDDEN_ITEM_ALARM_EVENT.getCode());
        bo.setReportTime(forbiddenItemEvent.getTimestamp());
        bo.setRemark(ElevatorEventTypeEnum.FORBIDDEN_ITEM_ALARM_EVENT.getDesc() + ":" + forbiddenItemAlarmEnum.getDesc());
        bo.setOssId(upload.getOssId());
        elevatorEventService.insertByBo(bo, true);
    }
}
